package cn.work.control;
import cn.work.bean.servicebean;
import cn.work.dao.serviceDao;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "ServiceListServlet", value = "/ServiceListServlet")
public class ServiceListServlet extends HttpServlet {
    private serviceDao serviceDAO = new serviceDao();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("ServiceListServlet 已接收到请求"); // 调试信息
        try {
            List<servicebean> services = serviceDAO.getAllServices();
            // 将结果转换为 JSON 格式
            Gson gson = new Gson();
            String json = gson.toJson(services);

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(json);
        } catch (SQLException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("Error retrieving services: " + e.getMessage());
        }
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}